﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DBLibrary;
using System.Xml;
using Common;
using System.Text;

public static class KeyHelper
{
    private static DateTime mLastRetrieveTime = DateTime.MinValue;

    public static KeyDetail GetFreeKey(KeyUsageType usageType)
    {
        KeyDetail result = null;
        List<KeyDetail> list = PoseidonDBHelper.AdminDB.Select<KeyDetail>(new DBParam("Type", (int)usageType));
        foreach (KeyDetail kd in list)
        {
            if (!kd.IsInUse)
            {
                result = kd;
                break;
            }
        }
        return result;
    }

    public static void RetrieveTemporaryKeys()
    {
        if (mLastRetrieveTime.AddDays(1) < DateTime.Now)
        {
            mLastRetrieveTime = DateTime.Now.AddDays(1);
            DB db = PoseidonDBHelper.AdminDB;
            List<KeyDetail> list = db.Select<KeyDetail>();
            List<KeyDetail> updateList = new List<KeyDetail>();
            foreach (KeyDetail kd in list)
            {
                if (kd.IsInUse && ((kd.UsageType & KeyUsageType.Temporary) == KeyUsageType.Temporary))
                {
                    KeyContent kc = kd.KeyContent;
                    if (kc.StartTime > kc.ExpireTime)
                    {
                        updateList.Add(kd);
                    }
                }
            }
            foreach (KeyDetail kd in updateList)
            {
                kd.IsInUse = false;
                kd.DBPre = string.Empty;
                db.Update(kd, "KeyId");
            }
        }
    }

    public static KeyDetail GenerateNewKeyDetail(KeyDetail kd)
    {
        KeyDetail newKd = new KeyDetail();
        newKd.KeyId = kd.KeyId;
        newKd.IsInUse = false;
        newKd.UsageTypeInt = kd.UsageTypeInt;
        newKd.Content = GenerageContentString(new KeyContent());
        return newKd;
    }

    public static KeyContent GenerateKeyContent(string content)
    {
        byte[] buf = Encoding.UTF8.GetBytes(content);
        return Serializer.BinaryDeSerialize<KeyContent>(buf);
        //KeyContent kc = new KeyContent();
        //XmlDocument doc = new XmlDocument();
        //doc.LoadXml(content);
        //foreach (XmlElement el in doc.DocumentElement.ChildNodes)
        //{
        //    switch (el.Name.ToLower())
        //    {
        //        case "starttime":
        //            kc.StartTime = new DateTime(long.Parse(el.GetAttribute("value")));
        //            break;
        //        case "expiretime":
        //            kc.ExpireTime = new DateTime(long.Parse(el.GetAttribute("value")));
        //            break;
        //    }
        //}
        //return kc;
    }

    public static string UpdateKeyContentString(string content ,string attName, object attVal)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(content);
        foreach (XmlElement el in doc.DocumentElement.ChildNodes)
        {
            if (el.Name.Equals(attName, StringComparison.OrdinalIgnoreCase))
            {
                el.SetAttribute(attName, attVal.ToString());
                break;
            } 
        }
        return doc.DocumentElement.OuterXml;
    }

    public static string GenerageContentString(KeyContent kc)
    {
        byte[] buf = Serializer.BinarySerialize(kc);
        return Encoding.UTF8.GetString(buf);
        //XmlDocument doc = new XmlDocument();
        //XmlElement rootEl = doc.CreateElement("Content");

        //XmlElement stEl = doc.CreateElement("StartTime");
        //stEl.SetAttribute("value", kc.StartTime.Ticks.ToString());
        //rootEl.AppendChild(stEl);

        //XmlElement etEl = doc.CreateElement("ExpireTime");
        //etEl.SetAttribute("value", kc.ExpireTime.Ticks.ToString());
        //rootEl.AppendChild(etEl);

        //return rootEl.OuterXml;
    }
}